//
// Created by 文道江 on 15/12/21.
// Copyright (c) 2015 文道江. All rights reserved.
//

#import "HybridFileAction.h"
#import "UploadManager.h"


@implementation HybridFileAction {

}

/**
 * 文件上传
 */
- (void)upload:(id)params {
    //TOOD: 后续添加录制时间,是否显示进度条等 可选参数
    NSString *url = params[@"file"];
    NSString *uploadUrl = params[@"uploadUrl"];
    NSURL *fileURL;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([url hasPrefix:@"file://"]){
        fileURL = [NSURL URLWithString:url];
    }else{
        fileURL = [NSURL fileURLWithPath:url];
    }
    if (![fileManager fileExistsAtPath:fileURL.relativePath]){
        [self callback:NO data:@"文件不存在!"];
        return;
    }


    NSDictionary *appInfo = [HybridBridge defaultHybridBridge].appInfo;

    if (!uploadUrl){
        if (IS_DEBUG){
            uploadUrl = appInfo[@"UploadDebugURL"];
        }else{
            uploadUrl = appInfo[@"UploadURL"];
        }
    }
    NSLog(@"uploadUrl: %@", uploadUrl);

    UploadManager *uploadManager = [UploadManager managerWithUploadURL:uploadUrl formName:@"file"];

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.controller.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.labelText = @"上传中...";
    [uploadManager uploadFile:fileURL parameters:@{} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [hud hide:YES];
        if (error == nil){
            NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            if([string hasPrefix:@"{"] && [string hasSuffix:@"}"]){
                NSError *err;
                NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&err];
                if (err == nil && dictionary[@"body"]){
                    if ([dictionary[@"isSuccess"] boolValue]){
                        [self callback:YES data:dictionary[@"body"]];
                    }else{
                        [self callback:NO data:dictionary[@"message"]];
                    }
                    return;
                }
            }
            [self callback:YES data:string];
        }else{
            if (responseObject){
                NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                [self callback:NO data:string];
            }else{
                [self callback:NO data:error.domain];
            }
        }
    } sendBodyDataBlock:^(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"... %lli, %lli, %lli", bytesSent, totalBytesSent, totalBytesExpectedToSend);
        float progress = (float)totalBytesSent / (float)totalBytesExpectedToSend;
        NSLog(@"upload progress: %f", progress);
        hud.progress = progress;
    }];
}

//TODO: 功能未完成
- (void)download:(id)params {

}

//TODO: 功能未完成
- (void)openFile:(id)params{

}

@end